//
//  RequestAlertPlugin.swift
//  CooperSwift
//
//  Created by Mac on 2019/12/4.
//  Copyright © 2019 CooperSwift. All rights reserved.
//

import Foundation
import Moya
import UIKit

public final class RequestAlertPlugin: PluginType {
    
    public init() {}
    
    // 开始发起请求
    public func willSend(_ request: RequestType, target: TargetType) { }
    
    // 收到结果
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        
        //只有请求错误时会继续往下执行
        guard case let Result.failure(error) = result else { return }
  
        //弹出并显示错误信息
        let url = target.baseURL.absoluteString + target.path
        let message = error.errorDescription ?? "未知错误"
        let alertViewController = UIAlertController(title: url,
                                                  message: "\(message)",
                                           preferredStyle: .alert)
        alertViewController.addAction(UIAlertAction(title: "复制", style: .destructive, handler: { _ in
            UIPasteboard.general.string = "\(url) \(message)"
        }))
        alertViewController.addAction(UIAlertAction(title: "确定", style: .default,
                                                  handler: nil))
        UIApplication.currentVC()?.present(alertViewController, animated: true)
        
    }
}
